import React from 'react';
import { View } from 'react-native';
import { Svg, Circle, Path } from 'react-native-svg';

const ColoredCircularProgress = ({ size, strokeWidth, segments }) => {
    const radius = size / 2 - strokeWidth / 2;
    const circumference = 2 * Math.PI * radius;
    const gapWidth = 2; // 间隔宽度
    const gapPercentage = gapWidth / circumference * 100; // 间隔所占的百分比

    // 计算每个段的路径
    const calculateSegmentPath = (startPercentage, endPercentage) => {
        // 调整结束百分比以添加间隔
        endPercentage -= gapPercentage;
        // 如果百分比为100%，则绘制一个完整的圆
        if (startPercentage === 0 && endPercentage >= 100 - gapPercentage) {
            // 使用两个半圆路径来创建一个完整的圆，以避免绘制问题
            return [
                `M ${size / 2},${size / 2 - radius}`,
                `a ${radius},${radius} 0 1,1 0,${2 * radius}`,
                `a ${radius},${radius} 0 1,1 0,${-2 * radius}`,
            ].join(' ');
        }

        // 原始的弧线路径计算
        const startAngle = (startPercentage / 100) * 2 * Math.PI - Math.PI / 2;
        const endAngle = (endPercentage / 100) * 2 * Math.PI - Math.PI / 2;
        const largeArcFlag = endPercentage - startPercentage <= 50 ? '0' : '1';

        const startX = size / 2 + radius * Math.cos(startAngle);
        const startY = size / 2 + radius * Math.sin(startAngle);
        const endX = size / 2 + radius * Math.cos(endAngle);
        const endY = size / 2 + radius * Math.sin(endAngle);

        return `M ${startX},${startY} A ${radius},${radius} 0 ${largeArcFlag} 1 ${endX},${endY}`;
    };
    // 计算每个段的起始和结束百分比
    let accumulatedPercentage = 0;
    const paths = segments.map((segment, index) => {
        const startPercentage = accumulatedPercentage;
        accumulatedPercentage += segment.percentage;
        const endPercentage = accumulatedPercentage;
        // 在最后一个段后不添加间隔
        // if (index < segments.length - 1) {
        //     accumulatedPercentage += gapPercentage;
        // }
        return {
            path: calculateSegmentPath(startPercentage, endPercentage),
            color: segment.color,
        };
    });

    return (
        <View style={{ justifyContent: 'center', alignItems: 'center' }}>
            <Svg height={size} width={size}>
                <Circle
                    cx={size / 2}
                    cy={size / 2}
                    r={radius}
                    fill="none"
                    stroke="#fff" // 白色边框
                    strokeWidth={strokeWidth}
                />
                {paths.map((segment, index) => (
                    <Path
                        key={index}
                        d={segment.path}
                        fill="none"
                        stroke={segment.color}
                        strokeWidth={strokeWidth}
                    />
                ))}
            </Svg>
        </View>
    );
};

export default ColoredCircularProgress;